<?php
//some operations may take a while
set_time_limit(180);
session_start();

//max amount of files for recursion. Used in search functions and dir size calculation
$filesLimit = 10000;
//use cache
$cache = true;

//authorization. Comment this variables to disable authorization
$username = "admin";
$password = "admin";

//show owner column or not
$showOwner = true;
//show permission column or not
$showPerms = true;
//show date column
$showDate = true;
//show size column
$showSize = true;

//disable showOwner, when not available 
if (!function_exists('posix_getpwuid') || !function_exists('posix_getgrgid')) {
  $showOwner = false;
}
if (isset($username) && isset($password)) {

  if (isset($_GET['logout'])) {
    unset($_SESSION["login"]);
    session_destroy();
  }

  if ($_POST['login'] == $username && $_POST['pass'] == $password) {
    $_SESSION['login'] = true;
  }

}
if ($_GET['a'] == "ico" && $_GET['i'] != "")
  showIcon($_GET['i']);

if (isset($_POST['chmodNum'])) {
  //do chmod and die
  die(@chmod($_POST['file'], octdec($_POST['chmodNum'])));
}

if (isset($_POST['newName'])) {
  //do rename and die
  die(@rename($_POST['file'], $_POST['newName']));
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>k-fm</title>
  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/redmond/jquery-ui.css"
        type="text/css" media="all"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js" type="text/javascript"></script>
  <style type="text/css">
    /*<![CDATA[*/
    body, td {
      font-family: Arial;
      font-size: 12px;
    }

    a {
      text-decoration: none;
      color: #6793C0;
    }

    a:hover {
      text-decoration: underline;
    }

    input[type=text], input[type=password] {
      border: 1px solid #EEEEEE;
      width: 300px;
      margin-right: 5px;
    }

    input[type=submit] {
      border: 1px solid #EEEEEE;
      width: 150px;
      background: #D4D0C8;
    }

    textarea {
      width: 100%;
      border: 1px solid #EEEEEE;
    }

    .nowrap {
      padding: 0 3px;
      width: 100px;
      white-space: nowrap;
    }

    th {
      background: #C1DCF8;
    }

    .back {
      background: #C1DCF8;
    }

    #chmod, #rename {
      display: none;
    }

    img {
      border: none;
    }

    #chmod input {
      width: 75px;
    }

    #rename input {
      width: 270px;
    }

    .fullFile, #dialog {
      display: none;
    }

    /*]]>*/
  </style>
  <script type="text/javascript">
    $(function() {

      $("#chmod").dialog({
        modal: true,
        autoOpen: false,
        title: 'Permissions',
        buttons: {
          Save: function() {
            $.ajax({
              type: "POST",
              url: '<?=$_SERVER['PHP_SELF']?>',
              data: $('#chmodForm').serialize(),
              success: function(html) {
                if (html == "1")
                  msg('Permission changed<br/>Please refresh page to see changes');
                else
                  msg('Operation failed');
              }
            });
            $(this).dialog('close');
          }
        }
      })
        ;
      $('.chmod').click(function() {
        $('input[name=file]').val($('.fullFile', $(this).parent()).html());
        $('input[name=chmodNum]').val($(this).html().match(/\(([\d]{4})\)/i).pop());
        $("#chmod").dialog('open');
      });

      $("#rename").dialog({
        modal: true,
        autoOpen: false,
        title: 'Rename, move',
        buttons: {
          Save: function() {
            $.ajax({
              type: "POST",
              url: '<?=$_SERVER['PHP_SELF']?>',
              data: $('#renameForm').serialize(),
              success: function(html) {
                if (html == "1")
                  msg('Rename successfull<br/>Please refresh page to see changes');
                else
                  msg('Operation failed' + html);
              }
            });
            $(this).dialog('close');
          }
        }
      })
        ;
      $('.rename').click(function() {
        $('input[name=file]').val($('.fullFile', $(this).parents('tr:first')).html());
        $('input[name=newName]').val($('.fullFile', $(this).parents('tr:first')).html());
        $("#rename").dialog('open');
      });

      function msg(text) {
        $('#dialog').html(text);
        $("#dialog").dialog({
          modal: true,
          buttons: {
            Ok: function() {
              $(this).dialog('close');
            }
          }
        });
      }
    })
      ;
  </script>
</head>
<body>
<?php

//Disable magic quotes
if (get_magic_quotes_gpc()) {
  $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
  while (list($key, $val) = each($process)) {
    foreach ($val as $k => $v) {
      unset($process[$key][$k]);
      if (is_array($v)) {
        $process[$key][stripslashes($k)] = $v;
        $process[] = &$process[$key][stripslashes($k)];
      } else {
        $process[$key][stripslashes($k)] = stripslashes($v);
      }
    }
  }
  unset($process);
}

if ($_POST['Save'] == "Save" && $_POST['a'] == "edit") {
  //save edited file
  if ($fh = fopen($_POST['f'], "w")) {
    if (fwrite($fh, $_POST['edited'])) {
      echo "File saved successfully<br/>\n";
    } else {
      echo "Error saving file<br/>\n";
    }
    fclose($fh);
  } else {
    echo "Can't open " . $_POST['f'] . " for writing<br/>\n";

  }
  $_GET['p'] = $_POST['p'];
  unset($_POST);
}

if ($_GET['a'] == "clearCache") {
  clearCache();
}

/*
Returns array of files witch contains $what
*/
function findInFiles($what, $where = "./") {
  if (substr($what, 0, 1) != "/")$what = "/$what/";
  $files = getFiles($where);
  foreach ($files as $file) {
    $contents = file_get_contents($file);
    if (preg_match_all($what, $contents, $result)) {
      foreach ($result[0] as $str) {
        $out['f'][$file] = snip($str, $contents);
      }
    }
  }
  fileList($out);
}

/*
Returns array of files witch name contains $what
*/
function findFiles($what, $where = "./") {
  if (substr($what, 0, 1) != "/")$what = "/$what/";
  $files = getFiles($where, array('.', '..'), false);
  foreach ($files as $file) {
    if (preg_match($what, $file)) {
      $out['f'][$file] = $file;
    }
  }
  fileList($out);
}

/*
Returns array of snippets containing $str from $contents
used in find feature
*/
function snip($str, $contents) {
  $out = array();
  $start = -1;
  do {
    $start = strpos($contents, $str, $start + 1);
    if ($start!==false)
      $out[$start] = str_replace(htmlentities($str), "<strong>" . htmlentities($str) . "</strong>", htmlentities(substr($contents, $start - 25, strlen($str) + 50)));
  }
  while ($start!==false);
  return $out;
}

/*
Returns array of files in $directory excluding $exempt
*/
function getFiles($directory, $exempt = array('.', '..', '.ds_store', '.svn', '.jpg', '.gif', '.png', '.avi', '.tgz', '.zip', '.tar', '.jpeg'), $noBinary = true, $level = 0, &$files = array()) {
  global $filesLimit, $cache;
  if ($cache) {
    $cacheFile = $directory . serialize($exempt);
    if ($noBinary)
      $cacheFile = md5($directory . serialize($exempt) . "1");
    else
      $cacheFile = md5($directory . serialize($exempt) . "0");
    if ($cached = getCache($cacheFile))
      return $cached;
  }
  if (count($files) > $filesLimit)
    return $files;
  if (substr($directory, -1) != "/")$directory .= "/";
  if (is_readable($directory)) {
    $handle = opendir($directory);
    while (false !== ($resource = readdir($handle))) {
      if (!in_array(substr(strtolower($resource), strrpos($resource, "."), 10), $exempt)) {
        if (is_dir($directory . $resource . '/'))
          array_merge($files, getFiles($directory . $resource . '/', $exempt, $noBinary, $level++, $files));
        else
          if ($noBinary && isBinary($directory . $resource))
            continue;
          else
            $files[] = $directory . $resource;
      }
    }
    closedir($handle);
  }
  return $files;
}

/*
Outputs file list
*/
function fileList($files) {
  global $path, $showOwner, $showPerms, $showDate, $showSize;
  echo '<div class="back"><table width="100%" cellspacing=1 cellpadding=1>';
  echo '<tr><th width="50%">Name</th><th width="50px">Type</th>';
  if ($showSize)
    echo '<th class="nowrap">Size</th>';
  if ($showOwner)
    echo '<th class="nowrap">Owner</th>';
  if ($showPerms)
    echo '<th class="nowrap">Permissions</th>';
  if ($showDate)
    echo '<th class="nowrap">Date</th>';
  echo '<th>Action</th></tr>';
  if (is_array($files['d'])) {
    asort($files['d']);
    foreach ($files['d'] as $dir => $arr) {
      if ($showSize) {
        $size = dirSize($path . "/" . $dir);
      }
      if ($bgColor == "" || $bgColor == "#FFFFFF")$bgColor = "#EEEEEE"; else $bgColor = "#FFFFFF";
      echo "<tr bgcolor=\"" . $bgColor . "\"><td><a href=\"" . $_SERVER['PHP_SELF'] . "?p=" . $path . "/" . $dir . "\"><span class=\"fileName\">$dir</span><span class=\"fullFile\">$dir</span></a></td><td>&lt;dir&gt;</td>";
      if ($showSize) {
        echo "<td class=\"nowrap\">" . convertSize($size[0]) . " in <span style=\"display:inline-block;width:60px\">" . $size[1] . "</span> files</td>";
      }
      if ($showOwner) {
        $owner = posix_getpwuid(fileowner($path . "/" . $dir));
        $group = posix_getgrgid(filegroup($path . "/" . $dir));
        echo "<td class=\"nowrap\">" . $owner['name'] . " : " . $group['name'] . "</td>";
      }
      if ($showPerms) {
        echo "<td class=\"nowrap chmod\">" . getPerms($path . "/" . $dir) . "</td>";
      }
      if ($showDate) {
        echo "<td class=\"nowrap\">" . date("d.m.Y H:i:s", filemtime($path . "/" . $dir)) . "</td>";
      }
      echo "<td class=\"nowrap\">&nbsp;</td></tr>\n";
      flush();
    }
  }
  if (is_array($files['f'])) {
    asort($files['f']);
    foreach ($files['f'] as $file => $arr) {
      if (substr($file, 0, 1) != "/")
        $fullFile = $path . "/" . $file;
      else $fullFile = $file;
      if ($bgColor == "" || $bgColor == "#FFFFFF")$bgColor = "#EEEEEE"; else $bgColor = "#FFFFFF";
      echo "<tr bgcolor=\"" . $bgColor . "\"><td><span class=\"fileName\">$file</span><span class=\"fullFile\">$fullFile</span>";
      if (is_array($arr))
        foreach ($arr as $line => $snip)
          echo "<br/>  Line: $line, Match: $snip";
      echo "</td><td>&lt;file&gt;</td>";
      if ($showSize)
        echo "<td class=\"nowrap\">" . convertSize(filesize($fullFile)) . "</td>";
      if ($showOwner) {
        $owner = posix_getpwuid(fileowner($fullFile));
        $group = posix_getgrgid(filegroup($fullFile));
        echo "<td class=\"nowrap\">" . $owner['name'] . " : " . $group['name'] . "</td>";
      }
      if ($showPerms) {
        echo "<td class=\"nowrap chmod\">" . getPerms($fullFile) . "</td>";
      }
      if ($showDate) {
        echo "<td class=\"nowrap\">" . date("d.m.Y H:i:s", filemtime($fullFile)) . "</td>";
      }
      echo "<td class=\"nowrap\"><a href=\"" . $_SERVER['PHP_SELF'] . "?f=" . $fullFile . "&amp;a=edit&amp;p=" . $path . "\"><img src=\"" . $_SERVER['PHP_SELF'] . "?a=ico&amp;i=edit\" alt=\"Edit\"></a><img class=\"rename\" src=\"" . $_SERVER['PHP_SELF'] . "?a=ico&amp;i=rename\" alt=\"Rename\" title=\"Rename\"/><a href=\"" . $_SERVER['PHP_SELF'] . "?f=" . $fullFile . "&amp;a=delete&amp;p=" . $path . "\" onclick=\"javascript:return confirm('Are you sure you want to delete " . $file . " ?')\"><img src=\"" . $_SERVER['PHP_SELF'] . "?a=ico&amp;i=remove\" alt=\"Delete file\"></a></td></tr>\n";
      flush();
    }
    echo '</table></div>';
  }

}

/*
Attempt to detect Binary file
*/
function isBinary($file) {
  $fh = fopen($file, "r");
  $blk = fread($fh, 512);
  fclose($fh);
  return (
    0 or substr_count($blk, "^ -~", "^\r\n") / 512 > 0.3
    or substr_count($blk, "\x00") > 0
    );
  return 0;
}

/*
Clickable breadcrumbs for easy navigation
*/
function breadcrumbs($path, $file = "") {
  $out = '';
  if (substr($path, 0, 1) == ".")
    $root = $_SERVER['DOCUMENT_ROOT'] . $path;
  else
    $root = $path;
  $arr = explode("/", $root);
  $p = '';
  foreach ($arr as $dir) {
    $dir = trim($dir, ".");
    if (strlen($dir) > 0) {
      $p .= "/$dir";
      $out .= "/<a href='" . $_SERVER['PHP_SELF'] . "?p=" . $p . "'>$dir</a>";
    }
  }
  if ($file != "")
    $out .= "/" . substr($file, strrpos($file, "/") + 1, strlen($file));
  return $out;
}

/*
Convert $size bytes into human readable value
*/
function convertSize($size) {
  $sizeName = array(" <span style=\"color:#737F65\">Bytes</span>", " <span style=\"color:#147F65\">Kb</span>", " <span style=\"color:#3A90ED\">Mb</span>", " Gb", " Tb", " Pb", " Eb", " Zb", " Yb");
  return $size ? "<span style=\"display:inline-block; width:60px\">" . round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . "</span><span style=\"display:inline-block; width:40px\">" . $sizeName[$i] . "</span>" : '<span style="display:inline-block; width:60px">0</span><span style="display:inline-block; width:40px">' . $sizeName[0] . '</span>';
}

/*
Calculate $directory size
*/
function dirSize($directory) {
  global $cache;
  if ($cache) {
    if ($size = getCache(md5("size-" . $directory)))
      return $size;
  }
  $size = 0;
  $files = getFiles($directory, array('.', '..'), false);
  if ($cache) {
    createCache(md5($directory . serialize(array('.', '..')) . "0"), $files);
  }
  foreach ($files as $file) {
    $size += filesize($file);
  }
  if ($cache) {
    createCache(md5("size-" . $directory), array($size, count($files)));
  }
  return array($size, count($files));
}

/*
Create cache $file with $data inside
*/
function createCache($file, $data) {
  $fh = fopen(sys_get_temp_dir() . "/k-fm." . $file, "w");
  fwrite($fh, serialize($data));
  fclose($fh);
}

/*
Retrieve cached data from $file
*/
function getCache($file) {
  if (file_exists(sys_get_temp_dir() . "/k-fm." . $file))
    return unserialize(file_get_contents(sys_get_temp_dir() . "/k-fm." . $file));
  else
    return false;
}

/*
Clear all cached data
*/
function clearCache() {
  $handle = opendir(sys_get_temp_dir());
  while (false !== ($resource = readdir($handle))) {
    if (substr_count($resource, "k-fm.") > 0) {
      unlink(sys_get_temp_dir() . "/" . $resource);
    }
  }
  closedir($handle);
  clearstatcache();
}

/*
Display login form
*/
function loginForm() {
  echo "<form method=\"POST\" action=\"" . $_SERVER['PHP_SELF'] . "\">\n";
  echo "<input type=\"text\" name=\"login\" value=\"login\">\n";
  echo "<input type=\"password\" name=\"pass\" value=\"123\">\n";
  echo "<input type=\"submit\" name=\"Login\" value=\"Login\">\n";
  echo "</form>\n";
}

/*
Get permissions of given $file or directory
*/
function getPerms($file) {
  if ($perms = fileperms($file)) {

    if (($perms & 0xC000) == 0xC000) {
      // Socket
      $info = 's';
    } elseif (($perms & 0xA000) == 0xA000) {
      // Symbolic Link
      $info = 'l';
    } elseif (($perms & 0x8000) == 0x8000) {
      // Regular
      $info = '-';
    } elseif (($perms & 0x6000) == 0x6000) {
      // Block special
      $info = 'b';
    } elseif (($perms & 0x4000) == 0x4000) {
      // Directory
      $info = 'd';
    } elseif (($perms & 0x2000) == 0x2000) {
      // Character special
      $info = 'c';
    } elseif (($perms & 0x1000) == 0x1000) {
      // FIFO pipe
      $info = 'p';
    } else {
      // Unknown
      $info = 'u';
    }

    // Owner
    $info .= (($perms & 0x0100) ? 'r' : '-');
    $info .= (($perms & 0x0080) ? 'w' : '-');
    $info .= (($perms & 0x0040) ?
      (($perms & 0x0800) ? 's' : 'x') :
      (($perms & 0x0800) ? 'S' : '-'));

    // Group
    $info .= (($perms & 0x0020) ? 'r' : '-');
    $info .= (($perms & 0x0010) ? 'w' : '-');
    $info .= (($perms & 0x0008) ?
      (($perms & 0x0400) ? 's' : 'x') :
      (($perms & 0x0400) ? 'S' : '-'));

    // World
    $info .= (($perms & 0x0004) ? 'r' : '-');
    $info .= (($perms & 0x0002) ? 'w' : '-');
    $info .= (($perms & 0x0001) ?
      (($perms & 0x0200) ? 't' : 'x') :
      (($perms & 0x0200) ? 'T' : '-'));
    return $info . " (" . substr(sprintf('%o', $perms), -4) . ")";
  }
  else
    return false;
}

/*
Display icon function. Icons by Aesthetica
*/
function showIcon($ico) {

  $icons['edit'] = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAI6SURBVHjajJNNS9VBFMZ/M/+5L+pVU1KildqL5CIhEHMZFNjCjxBU25bt+wDtgmoV9AGilRsjqYXpsgghFFO8VmLkQs379p+Zc1r8r96buejAcGCY85znPM8ZM/d+cbKnuzTtEmsBpRmqoKqIiq1U6y8q1dqWdQm69o7d1e/E17OYXILr7SlNjY+NPuooFiwnIsRImnq2fuzcXC9/uxFFG6gi3tskhj7NuX0LCKiqKiLCURYRrDEkScK5wbNT169dnVWJpNXflMYnH/aOXNrOeX/fZXyzjsaY46yaXSaJJYRAqavz1sjw0NNKOVnvmpp6vBzdXOPlsyV3RLe96GQUiwUO6pG+vS8PRoYH2Fl8Pp/+7JwhnwuW/wjjCpjNJbp3P7Nb3ni7fVCfyXeUQq5/ANdS/fTuahMaqx9w5QU8RTZG77yqpFI/Y4CJ22QMTAvk6GTFlsrKAubrPMF0UJu4h813YlpuY1WVEIWTBNRa6pufkJU3RM2RTtxFTYJKaHukOBHF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PUVRsDn7ADU/RfTxFaNjJ4mTGmIVOGuJgxArFSg3Ut0LaG3wlGSNCdTiDO7gGVw6DnmG8SUigHOWOAq6oLwoMB0yD7QaE/DhGTJ8gvDcNcKlVbQCUSCiQUQInEM6d0thuiY2G5Pw/ikMHsOevgpKM5QmuMChaSIG6K8lHBgp0bryvPSeWq1G+80Ufv4xds8YwdnrGBcC0J/0VWEDxCgYqNcZqNd7Urb2/SuLiwuMHL1IfOoK6J3JtFohKs9cmW1R9CaZ1vYmweHzuP2jZHkbvN/xmVSROZlfWV+YbP5o578RGG1Q2pIvv+tY2VuiYGndL/8cAOvZr8GTsO4BAAAAAElFTkSuQmCC';

  if (isset($icons[$ico])) {
    $icon = base64_decode($icons[$ico]);
    header('Content-Type: image/png');
    die($icon);
  }
}

if (isset($username) && isset($password)) {
  if (empty($_SESSION['login'])) {
    echo loginForm();
    die('</body></html>');
  }
}
$path = $_GET['p'];
if (empty($path))$path = ".";

if ($_GET['a'] == "delete") {
  if (@unlink($_GET['f']))
    echo $_GET['f'] . " deleted <br/>\n";
  else
    echo "Deletion of " . $_GET['f'] . " <strong>failed</strong><br/>\n";
  unset($_GET['f']);
}

$breadcrumbs = breadcrumbs($path, $_GET['f']) . "<br>\n";
if (isset($username) && isset($password) && isset($_SESSION['login']))
  echo "[<a href=\"" . $_SERVER['PHP_SELF'] . "?logout\">logout</a>] ";
if ($cache)
  echo "[<a href=\"" . $_SERVER['PHP_SELF'] . "?a=clearCache&amp;p=" . $path . "\">clear cache</a>]";
?>

<form method="GET" action="<?=$_SERVER['PHP_SELF']?>">
  <input type="text" name="q" value="<?=$_GET['q']?>"><input type="text" name="p" value="<?=$path?>"><input
  type="submit" name="Find in files" value="Find in files ">
</form>
<form method="GET" action="<?=$_SERVER['PHP_SELF']?>">
  <input type="text" name="qf" value="<?=$_GET['qf']?>"><input type="text" name="p" value="<?=$path?>"><input
  type="submit" name="Find files" value="Find files">
</form>

<?
echo $breadcrumbs;

if (!empty($_GET['q'])) {
  //search in files
  $q = trim($_GET['q']);
  if (strlen($q) < 3) {
    echo "Search string too short";
  }
  else
    findInFiles($q, $path);
}
elseif ($_GET['a'] == "edit") {
  //edit stuff here
  if (!isBinary($_GET['f'])) {
    echo "<form method=\"POST\" action=\"" . $_SERVER['PHP_SELF'] . "\">\n";
    echo "<textarea rows=20 cols=80 name=\"edited\">" . file_get_contents($_GET['f']) . "</textarea>\n";
    echo "<input type=\"hidden\" name=\"p\" value=\"" . $path . "\" >\n";
    echo "<input type=\"hidden\" name=\"f\" value=\"" . $_GET['f'] . "\" >\n";
    echo "<input type=\"hidden\" name=\"a\" value=\"edit\" >\n";
    echo "<br/><input type=\"submit\" name=\"Save\" value=\"Save\">\n";
    echo "</form>";
  } else {
    echo "Can't edit binary file<br/>\n";
  }
}
elseif (!empty($_GET['qf'])) {
  //search for a file
  $qf = trim($_GET['qf']);
  if (strlen($qf) < 3) {
    echo "Search string too short";
  }
  else
    findFiles($qf, $path);
}
else {
  //default: file list
  $handle = opendir($path);
  $out = array();
  while (false !== ($resource = readdir($handle))) {
    if ($resource != "." && $resource != "..")
      $out[is_file($path . "/" . $resource) ? "f" : "d"][$resource] = $path . "/" . $resource;
  }
  closedir($handle);
  fileList($out);
}
echo $breadcrumbs;

?>
<div id="chmod">
  <form method="POST" id="chmodForm" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="text" name="chmodNum" size=4>
    <input type="hidden" name="file">
  </form>
</div>
<div id="dialog">

</div>

<div id="rename">
  <form method="POST" id="renameForm" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="text" name="newName">
    <input type="hidden" name="file">
    <input type="hidden" name="p" value="<?=$p?>">
  </form>
</div>

</body>
</html>